package com.tanhua.dubbo.api.mongo;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.utils.IdService;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;


@Service
public class PublishApiImpl implements PublishApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Override
    public String save(Publish publish) {
        //1、保存到publish总记录表中  ：Publish
        publish.setId(ObjectId.get());
        publish.setPid(idService.getNextId("quanzi_publish"));
        publish.setCreated(System.currentTimeMillis()); //当前时间的毫秒  1000  2000  2001
        mongoTemplate.save(publish);
        //2、保存到自己的动态信息表中  ：Album
        Album album = new Album();
        album.setId(ObjectId.get());
        album.setPublishId(publish.getId());
        album.setCreated(System.currentTimeMillis());
        mongoTemplate.save(album,"quanzi_album_"+publish.getUserId());
        //3、查询当前用户的所有好友    ：Friend
        Query query = new Query(Criteria.where("userId").is(publish.getUserId()));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        //4、向每个好友的时间线表中保存动态记录 ：TimeLine
        if(friends != null) {
            for (Friend friend : friends) {
                TimeLine timeLine = new TimeLine();
                timeLine.setId(ObjectId.get());
                timeLine.setPublishId(publish.getId());
                timeLine.setCreated(System.currentTimeMillis());
                timeLine.setUserId(publish.getUserId());
                mongoTemplate.save(timeLine,"quanzi_time_line_"+friend.getFriendId());
            }
        }
        return publish.getId().toHexString();
    }

    //查询好友的动态，登录用户的id
    public PageResult findAllByTimeline(int page, int size, Long userId) {
        //1、查询时间线表，根据当前用户，查询此用户的时间表
        Query query = new Query().with(Sort.by(Sort.Order.desc("created")))
                .limit(size).skip((page-1) * size);
        //publishId : 动态详情的id
        List<TimeLine> lines = mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);
        long counts = mongoTemplate.count(query, TimeLine.class, "quanzi_time_line_" + userId);
        //2、循环时间线数据，查询publish，获取动态详情
        List<Publish> list = new ArrayList<>();
        for (TimeLine line : lines) {
            Publish publish = mongoTemplate.findById(line.getPublishId(), Publish.class);
            list.add(publish);
        }
        //3、构造返回值
        return new PageResult(page,size,(int) counts,list);
    }

    //根据用户id，查询推荐的动态 （推荐表）
    public PageResult findAllByRecommend(int page, int size, Long userId) {
        //1、查询推荐表，根据用户id查询  RecommendQuanzi
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")))
                .limit(size).skip((page-1) * size);

        List<RecommendQuanzi> recommends = mongoTemplate.find(query, RecommendQuanzi.class);
        long counts = mongoTemplate.count(query, RecommendQuanzi.class);
        //2、根据推荐的数据，查询动态详情 publish
        List<Publish> list = new ArrayList<>();
        for (RecommendQuanzi recommend : recommends) {
            Publish publish = mongoTemplate.findById(recommend.getPublishId(), Publish.class);
            list.add(publish);
        }
        //3、构造返回值
        return new PageResult(page,size,(int) counts,list);
    }

    /**
     * 查询自己的动态列表
     */
    public PageResult findAllByAlbum(Integer page, Integer pagesize, Long userId) {
        //1、拼接数据库表明
        String collectioName = "quanzi_album_"+userId;
        //2、分页查询（设置排序）   List<Album> list
        Query query = new Query().limit(pagesize).skip((page-1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Album> albums = mongoTemplate.find(query, Album.class, collectioName);
        long count = mongoTemplate.count(query, Album.class, collectioName);
        //3、循环自己的所有时间线数据，查询动态明细publish
        List<Publish> list = new ArrayList<>();
        for (Album album : albums) {
            Publish publish = mongoTemplate.findById(album.getPublishId(), Publish.class);
            if(publish.getState() == 1) {
                list.add(publish); //只查询状态未审核通过的动态
            }
        }
        //4、构造返回
        return new PageResult(page,pagesize, (int) count,list);
    }

    //根据id，查询动态
    public Publish findById(String publishId) {
        return mongoTemplate.findById(new ObjectId(publishId),Publish.class);
    }

    @Override
    public PageResult findAll(int page, int pagesize, Long uid, Integer state) {

        Query query = new Query();

        if(uid != null) {
            query.addCriteria(Criteria.where("userId").is(uid));
        }

        List<Publish> list = mongoTemplate.find(query, Publish.class);
        long count = mongoTemplate.count(query, Publish.class);

        return new PageResult(page,pagesize, (int) count,list);
    }

    //根据动态id，更新状态
    public void updateState(String id, Integer state) {
        Query query = Query.query(Criteria.where("id").is(new ObjectId(id)));
        Update update = Update.update("state",state);
        mongoTemplate.updateFirst(query,update,Publish.class);
    }

    @Override
    public List<Publish> findByPids(List<Long> pidList) {
        Query query = Query.query(Criteria.where("pid").in(pidList));
        return mongoTemplate.find(query, Publish.class);
    }
}

